package cc.ufinity.networkdiagnose.widget;

import java.lang.reflect.Field;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import cc.ufinity.networkdiagnose.app.GlobalApp;
import cc.ufinity.networkdiagnose.manager.FTPConfig;
import cc.ufinity.networkdiagnose.manager.MessageWhat;
import cc.ufinity.networkdiagnose.manager.NetworkManager;
import cc.ufinity.networkdiagnose.manager.Task;
import cc.ufinity.networkdiagnose.util.StringUtils;
import cc.ufinity.networkdiagnose.view.R;

public class SegregateTestWidgetProxy extends GeneralTestWidget {

    // private WlanManager wlanManager;
    private Activity ctx;
    private Handler handlerChild;
    private Handler handler;
    private Button btnBack;
    private Button btnStart;
    private EditText ipText;
    private int frequency = 10;
    private NetworkManager nm; 
    private boolean processing;
    private int current;
    private int successTimes;
    private Task task;
    public static int testFlag = 0;
    public static int taskFlag = 0;   
	private static String testIp; 
	private boolean isFirst = true;
	
    public SegregateTestWidgetProxy(Activity context, Handler handl) {
        super(context);
        inflate(context, R.layout.segregate_test_widget_proxy, this);
        this.ctx = context; 
        this.handlerChild = handl;
        btnBack = (Button) this.findViewById(R.id.segregate_test_proxy_btnback);
        btnStart = (Button) this.findViewById(R.id.btn_segregate_proxy_start); 
        ipText = (EditText) this.findViewById(R.id.text_segregateTest_proxy_pingaddress);
        btnStart.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                startTest();
            }
        });

        btnBack.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                backToTask(ctx);
            }
        });

        handler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case MessageWhat.DO_NEXT_TEST:
                    break;
                default:
                    updateResult(msg.what);
                    break;
                }
            }
        };

        // wlanManager = new WlanManager(ctx);
        nm = new NetworkManager();
        nm.setHandler(handler);
        // wlanManager.setHandler(handler);
        task = (Task) ctx.getIntent().getSerializableExtra(TAG_REFER_TASK);
        System.err.println(task.acIp+"==========================================================");
        frequency = task.testCount;
        inputUserPassDialog() ;
    }
    /**
     * 配置测试IP
     * @param ctx
     * @param wlanManager
     * @param handler
     */
    public void inputUserPassDialog() {
    	LayoutInflater factory = LayoutInflater.from(ctx);
		final View dialogView = factory.inflate(R.layout.segregate_input_ip_dialog, null);
		final EditText ipText = (EditText) dialogView.findViewById(R.id.text_segregateTest_proxy_pingaddress);  
	    String ip = task.acIp==null?"": task.acIp;
	    if(ip.length()>4 && ip.lastIndexOf(".")>0)
        	ip = ip.substring(0,ip.lastIndexOf(".")+1);
        ipText.setText(ip);
        ipText.setSelection(ip.length());
        AlertDialog.Builder builder = new AlertDialog.Builder(ctx); 
        builder.setTitle("隔离测试IP配置"); 
        builder.setView(dialogView); 
        builder.setCancelable(false); 
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
         	public void onClick(DialogInterface dialog, int id) {
	       		 testIp = ipText.getText().toString();  
	    		 try { 
	    			 Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
					 field.setAccessible(true);
	    			 if (StringUtils.isEmpty(testIp)) {
						field.set(dialog, false);
						showMessage(ctx, "请输入测试IP");
					 }else if (!StringUtils.isIPV4(testIp)) { 
						field.set(dialog, false);
		    			showMessage(ctx, "请输入正确的IPV4地址!");
					 }else{ 
						 field.set(dialog, true);  
						 startTest();
					 }
	    		 } catch (Exception e) {
						e.printStackTrace();
						showMessage(ctx, "配置失败，请稍后重试");
				 }
        	}
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener(){
        	public void onClick(DialogInterface dialog, int id) {
        		try {
					Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
					field.setAccessible(true);
					field.set(dialog, true);
				} catch (Exception e) {
					e.printStackTrace();
				}
				GlobalApp.result_SEGREGATE_test=new StringBuffer("\n\n隔离测试项已取消");
                //mSendBroadcast(ctx);
                handlerSendToTarget(handlerChild, MessageWhat.HANDLER_SEGRE);
        		dialog.cancel();
        	}
        });
	 	wifiListDialog = builder.create();
	    wifiListDialog.show(); 
 
    }
 
    /**
     * 用户隔离PING测试
     */
    private void startTest() {
        processing = false;
        current = 0;
        successTimes = 0; 
        final String ip = ipText.getText().toString();
       // if (StringUtils.isIPV4(ip)) {
        final FTPConfig ftp = this.getFTPConfig(ctx);
        if (ftp!=null && ftp.userName!=null && ftp.userName.length() > 0) {
         //   this.showProgressDialog(ctx, "正在进行隔离测试...", frequency);
            new Thread() {
                public void run() {
                    while (current < frequency) {
                        if (!processing) {
                            processing = true;
                            current++;
                            nm.ping(ip, 1, 64);
                        }
                    }
                }
            }.start();
        }
//        } else {
//            this.showMessage(ctx, "请输入正确的IPV4地址!");
//        }
    }

    private void updateResult(int msgWhat) {
    	//----------------------------------------------------------
		if(isFirst) {
			isFirst = false;
			StringBuffer temp = new StringBuffer();
			GlobalApp.result_SEGREGATE_test = temp;
		}
	//----------------------------------------------------------
        this.setDialogProgress(current);
        String res = nm.getPingResult(); 
        switch (msgWhat) {
        case MessageWhat.PING_SUCCESS: 
          //----------------------------------------------------------
			
			GlobalApp.result_SEGREGATE_test.append(res);
		
	//---------------------------------------------------------- 
            break;
        case MessageWhat.PING_FAILED:
            successTimes++;
            StringBuffer s = new StringBuffer();
            s.append("第").append(current).append("次 PING测试失败");
          //----------------------------------------------------------
			
			GlobalApp.result_SEGREGATE_test.append("第").append(current).append("次 PING测试失败\n");
	
		//---------------------------------------------------------- 
        }
        processing = false;
        if (current == frequency) {
            StringBuffer s = new StringBuffer();
            s.append("隔离测试总数：").append(frequency);
            s.append(" 隔离成功率：").append((successTimes / frequency) * 100).append('%');
          //----------------------------------------------------------
			
			GlobalApp.result_SEGREGATE_test.append("\n隔离测试总数：").append(frequency)
					.append("\n隔离成功率：").append((successTimes / frequency) * 100).append("%\n");

		//---------------------------------------------------------- 

            task.userIsolateSuccessRate = String.valueOf(((float)successTimes / frequency) * 100);
            
            task.userIsolateCount = frequency +"";
            task.userIsolateSuccessCount = successTimes +"";
            

System.out.println("task.userIsolateCount => " + task.userIsolateCount);
System.out.println("task.userIsolateSuccessCount => " + task.userIsolateSuccessCount);
System.out.println("task.userIsolateSuccessRate => " + task.userIsolateSuccessRate);
            
            ctx.getIntent().putExtra(TAG_REFER_TASK, task);

            dismissProgressDialog(); 
            handlerSendToTarget(handlerChild, MessageWhat.HANDLER_SEGRE);
        } 

    } 
}
